package com.lenovo.lcdm.dcm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.lenovo.lcdm.dcm.common.enums.BusinessMsgEnum;
import com.lenovo.lcdm.dcm.common.exception.DcmBusinessException;
import com.lenovo.lcdm.dcm.common.util.ContextUtil;
import com.lenovo.lcdm.dcm.common.util.VersionUtil;
import com.lenovo.lcdm.dcm.constant.DcmConstant;
import com.lenovo.lcdm.dcm.dto.DummyConfigurableModelCatagoryDto;
import com.lenovo.lcdm.dcm.dto.DummyConfigurableModelDto;
import com.lenovo.lcdm.dcm.dto.DummyConfigurableModelFeatureDto;
import com.lenovo.lcdm.dcm.entity.DummyConfigurableModel;
import com.lenovo.lcdm.dcm.entity.DummyConfigurableModelCategory;
import com.lenovo.lcdm.dcm.entity.DummyConfigurableModelMaster;
import com.lenovo.lcdm.dcm.entity.PortfolioOffering;
import com.lenovo.lcdm.dcm.mapper.DummyConfigurableModelMapper;
import com.lenovo.lcdm.dcm.service.*;
import com.lenovo.lcdm.dcm.vo.DcmHistoryVo;
import com.lenovo.lcdm.dcm.vo.DummyConfigurableModelCategoryVo;
import com.lenovo.lcdm.dcm.vo.DummyConfigurableModelVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author sunby1
 * @description 针对表【plm_dummy_configurable_model】的数据库操作Service实现
 * @createDate 2023-12-27 15:29:12
 */
@Service
public class DummyConfigurableModelServiceImpl extends ServiceImpl<DummyConfigurableModelMapper, DummyConfigurableModel> implements DummyConfigurableModelService {

    private final DummyConfigurableModelMasterService dummyConfigurableModelMasterService;
    private final DummyConfigurableModelCategoryService dummyConfigurableModelCategoryService;
    private final PortfolioOfferingService portfolioOfferingService;
    private final DummyConfigurableModelProductFeaturesDescService dummyConfigurableModelProductFeaturesDescService;
    private final DcmAttachmentLinkService dcmAttachmentLinkService;

    @Autowired
    public DummyConfigurableModelServiceImpl(DummyConfigurableModelMasterService dummyConfigurableModelMasterService,
                                             DummyConfigurableModelCategoryService dummyConfigurableModelCategoryService,
                                             PortfolioOfferingService portfolioOfferingService,
                                             DummyConfigurableModelProductFeaturesDescService dummyConfigurableModelProductFeaturesDescService,
                                             DcmAttachmentLinkService dcmAttachmentLinkService) {
        this.dummyConfigurableModelMasterService = dummyConfigurableModelMasterService;
        this.dummyConfigurableModelCategoryService = dummyConfigurableModelCategoryService;
        this.portfolioOfferingService = portfolioOfferingService;
        this.dummyConfigurableModelProductFeaturesDescService = dummyConfigurableModelProductFeaturesDescService;
        this.dcmAttachmentLinkService = dcmAttachmentLinkService;
    }

    @Override
    public Integer newVersion(DummyConfigurableModel oldDummyConfigurableModel) {
        Integer newId = 0;
        if (DcmConstant.DCM_STATUS_PUBLISHED.equals(oldDummyConfigurableModel.getState())) {
            newId = newMajorVersion(oldDummyConfigurableModel);
        } else {
            newId = newSecondaryVersion(oldDummyConfigurableModel);
        }
        copyLink(oldDummyConfigurableModel.getId().intValue(), newId);
        return newId;
    }

    private void copyLink(Integer oldId, Integer newId) {
        dummyConfigurableModelCategoryService.copyCategoriesByDcmId(oldId, newId);
    }

    @Override
    public DummyConfigurableModelVo getDcmById(DummyConfigurableModel dummyConfigurableModel) {
        DummyConfigurableModelVo dummyConfigurableModelVo = new DummyConfigurableModelVo();
        // 查master
        DummyConfigurableModelMaster dummyConfigurableModelMaster = dummyConfigurableModelMasterService.getById(dummyConfigurableModel.getMasterId());
        dummyConfigurableModelVo.setId(dummyConfigurableModel.getId());
        dummyConfigurableModelVo.setNumber(dummyConfigurableModelMaster.getNumber());
        dummyConfigurableModelVo.setName(dummyConfigurableModelMaster.getName());
        dummyConfigurableModelVo.setCreator(dummyConfigurableModelMaster.getCreator());
        dummyConfigurableModelVo.setModifier(dummyConfigurableModel.getModifier());
        dummyConfigurableModelVo.setLastestAll(dummyConfigurableModel.getLastestAll());
        dummyConfigurableModelVo.setCreateTime(dummyConfigurableModelMaster.getCreateTime());
        dummyConfigurableModelVo.setModifyTime(dummyConfigurableModel.getModifyTime());
        dummyConfigurableModelVo.setGeo(dummyConfigurableModel.getGeo());
        dummyConfigurableModelVo.setReferenceCtoNumber(dummyConfigurableModel.getReferenceCtoNumber());
        dummyConfigurableModelVo.setVersion(dummyConfigurableModel.getVersion() + "." + dummyConfigurableModel.getIteration());
        dummyConfigurableModelVo.setState(dummyConfigurableModel.getState());
        // 查 category
        List<DummyConfigurableModelCategoryVo> categoryVos = dummyConfigurableModelCategoryService.getCategoryVos(dummyConfigurableModel.getId());
        dummyConfigurableModelVo.setCategories(categoryVos);
        return dummyConfigurableModelVo;
    }

    @Override
    public void undoCheckout(DummyConfigurableModel dummyConfigurableModel) {
        DummyConfigurableModel delModel = this.getById(dummyConfigurableModel.getId());
        // 将上一个的last恢复
        DummyConfigurableModel oldDummyConfigurableModel = this.getById(delModel.getChangedFrom());
        lambdaUpdate().set(DummyConfigurableModel::getLastestAll, true)
                .set(DummyConfigurableModel::getLastest, 1)
                .set(DummyConfigurableModel::getCheckoutTime, null)
                .set(DummyConfigurableModel::getCheckoutBy, null)
                .set(DummyConfigurableModel::getCheckoutStatus, 0)
                .eq(DummyConfigurableModel::getId, oldDummyConfigurableModel.getId()).update();
        // 删除最新的
        this.removeById(dummyConfigurableModel.getId());
        // 删除link
        delLink(dummyConfigurableModel.getId());
    }

    @Override
    public List<DcmHistoryVo> getDcmHistoryByMasterId(Long masterId) {
        LambdaQueryWrapper<DummyConfigurableModel> dcmWrapper = new QueryWrapper<DummyConfigurableModel>().lambda();
        dcmWrapper.eq(DummyConfigurableModel::getMasterId, masterId);
        dcmWrapper.orderByDesc(DummyConfigurableModel::getId);
        List<DummyConfigurableModel> dummyConfigurableModels = this.getBaseMapper().selectList(dcmWrapper);
        return dummyConfigurableModels.stream().map(dcm -> {
            DcmHistoryVo dcmHistoryVo = new DcmHistoryVo();
            dcmHistoryVo.setId(dcm.getId());
            dcmHistoryVo.setVersion(dcm.getVersion() + "." + dcm.getIteration());
            dcmHistoryVo.setCreator(dcm.getCreator());
            dcmHistoryVo.setModifier(dcm.getModifier());
            dcmHistoryVo.setCreateTime(dcm.getCreateTime());
            dcmHistoryVo.setModifyTime(dcm.getModifyTime());
            dcmHistoryVo.setVersionRemark(dcm.getVersionRemark());
            dcmHistoryVo.setDocumentUrl(dcmAttachmentLinkService.getUrlByObjectIdAndName(dcm.getId(), DummyConfigurableModel.class.getName()));
            return dcmHistoryVo;
        }).toList();
    }

    @Override
    public Integer endVersion(DummyConfigurableModel oldDummyConfigurableModel) {
        DummyConfigurableModel newDummyConfigurableModel = copyNewDCM(oldDummyConfigurableModel);
        // 创建新的对象
        newDummyConfigurableModel.setIteration(oldDummyConfigurableModel.getIteration() + 1);
        newDummyConfigurableModel.setState("Published");
        newDummyConfigurableModel.setCheckoutStatus(0);
        newDummyConfigurableModel.setCheckoutBy(null);
        newDummyConfigurableModel.setVersionRemark("Updated by Publish action");
        Integer newId = this.getBaseMapper().insert(newDummyConfigurableModel);
        // 给老的版本设置非最新状态
        oldDummyConfigurableModel.setLastest(0);
        oldDummyConfigurableModel.setLastestAll(false);
        this.getBaseMapper().updateById(oldDummyConfigurableModel);
        copyLink(oldDummyConfigurableModel.getId().intValue(), newDummyConfigurableModel.getId().intValue());
        return newDummyConfigurableModel.getId().intValue();
    }

    @Override
    public DummyConfigurableModelDto getDcmDtoById(DummyConfigurableModel dummyConfigurableModel) {
        DummyConfigurableModelDto dummyConfigurableModelDto = new DummyConfigurableModelDto();
        // 查master
        DummyConfigurableModelMaster dummyConfigurableModelMaster = dummyConfigurableModelMasterService.getById(dummyConfigurableModel.getMasterId());
        dummyConfigurableModelDto.setId(dummyConfigurableModel.getId());
        dummyConfigurableModelDto.setProductSegment(dummyConfigurableModel.getProductSegment());
        dummyConfigurableModelDto.setBusinessSegment(dummyConfigurableModel.getBusinessSegment());
        dummyConfigurableModelDto.setName(dummyConfigurableModelMaster.getName());
        dummyConfigurableModelDto.setGeo(dummyConfigurableModel.getGeo());
        dummyConfigurableModelDto.setReferenceCtoNumber(dummyConfigurableModel.getReferenceCtoNumber());
        // 查 category
        List<DummyConfigurableModelCatagoryDto> categoryDtos = dummyConfigurableModelCategoryService.getCategoryDtos(dummyConfigurableModel.getId());
        dummyConfigurableModelDto.setDummyConfigurableModelCatagoryDtos(categoryDtos);
        return dummyConfigurableModelDto;
    }

    @Override
    public Long createDcm(DummyConfigurableModelDto dummyConfigurableModelDto) {
        // 保存master
        String number = genNumber();
        DummyConfigurableModelMaster dummyConfigurableModelMaster = new DummyConfigurableModelMaster();
        dummyConfigurableModelMaster.setNumber(number);
        dummyConfigurableModelMaster.setName(dummyConfigurableModelDto.getName());
        dummyConfigurableModelMaster.setCreator(ContextUtil.getCurrentUser());
        dummyConfigurableModelMaster.setModifier(ContextUtil.getCurrentUser());
        dummyConfigurableModelMaster.setCreateTime(DateUtil.date());
        dummyConfigurableModelMaster.setModifyTime(DateUtil.date());
        dummyConfigurableModelMaster.setDeleted(0);
        dummyConfigurableModelMasterService.save(dummyConfigurableModelMaster);
        // 保存dcm
        DummyConfigurableModel model = new DummyConfigurableModel();
        model.setReferenceCtoNumber(dummyConfigurableModelDto.getReferenceCtoNumber());
        model.setGeo(dummyConfigurableModelDto.getGeo());
        model.setProductSegment(dummyConfigurableModelDto.getProductSegment());
        model.setBusinessSegment(dummyConfigurableModelDto.getBusinessSegment());
        model.setCheckoutStatus(0);
        model.setVersion("A");
        model.setIteration(1);
        model.setBranchId(this.getBaseMapper().getBranchId());
        model.setMasterId(dummyConfigurableModelMaster.getId());
        model.setState(DcmConstant.DCM_STATUS_DRAFT);
        model.setLastest(1);
        model.setLastestAll(true);
        model.setCreateTime(DateUtil.date());
        model.setModifyTime(DateUtil.date());
        model.setDeleted(0);
        model.setProductSegment(getProductSegment(dummyConfigurableModelDto.getName()));
        model.setCreator(ContextUtil.getCurrentUser());
        model.setModifier(ContextUtil.getCurrentUser());
        model.setVersionRemark(dummyConfigurableModelDto.getVersionRemark());
        this.save(model);
        dummyConfigurableModelCategoryService.saveByDcmId(model.getId(), dummyConfigurableModelDto.getDummyConfigurableModelCatagoryDtos());
        return model.getId();
    }

    private String getProductSegment(String dcmName) {
        List<PortfolioOffering> list = portfolioOfferingService.lambdaQuery().eq(PortfolioOffering::getOfferingName, dcmName).list();
        Optional<PortfolioOffering> first = list.stream().findFirst();
        return first.map(PortfolioOffering::getProductSegment).orElse(null);
    }

    private String genNumber() {
        Long number = this.getBaseMapper().getNumber();
        NumberFormat formatter = NumberFormat.getNumberInstance();
        formatter.setMinimumIntegerDigits(DcmConstant.BUSINESS_CODE_LENGTH);
        formatter.setGroupingUsed(false);
        String value = formatter.format(number);
        return DcmConstant.BUSINESS_CODE_PREFIX + value;
    }

    @Override
    public void checkIn(DummyConfigurableModelDto dummyConfigurableModelDto) {
        LambdaUpdateWrapper<DummyConfigurableModel> updateWrapper = Wrappers.lambdaUpdate(DummyConfigurableModel.class)
                .set(DummyConfigurableModel::getCheckoutStatus, 0)
                .set(DummyConfigurableModel::getCheckoutTime, null)
                .set(DummyConfigurableModel::getCheckoutBy, null)
                .set(DummyConfigurableModel::getModifier, ContextUtil.getCurrentUser())
                .set(DummyConfigurableModel::getModifyTime, DateUtil.date())
                .set(DummyConfigurableModel::getVersionRemark, dummyConfigurableModelDto.getVersionRemark())
                .eq(DummyConfigurableModel::getId, dummyConfigurableModelDto.getId());
        if (StringUtils.isNotBlank(dummyConfigurableModelDto.getReferenceCtoNumber())) {
            updateWrapper.set(DummyConfigurableModel::getReferenceCtoNumber, dummyConfigurableModelDto.getReferenceCtoNumber());
        }
        this.update(updateWrapper);
//        dummyConfigurableModelProductFeaturesDescService.updateForCheckIn(dummyConfigurableModelDto);
    }

    @Override
    public DummyConfigurableModel getDcmByNameAndGeo(String name, String geo) {
        List<DummyConfigurableModelMaster> dummyConfigurableModelMasters = dummyConfigurableModelMasterService.lambdaQuery().eq(DummyConfigurableModelMaster::getName, name).list();
        if (CollectionUtil.isNotEmpty(dummyConfigurableModelMasters)) {
            List<Long> masterIds = dummyConfigurableModelMasters.stream().map(DummyConfigurableModelMaster::getId).toList();
            List<DummyConfigurableModel> dummyConfigurableModels = lambdaQuery().in(DummyConfigurableModel::getMasterId, masterIds)
                    .eq(DummyConfigurableModel::getLastestAll, true)
                    .eq(DummyConfigurableModel::getGeo, geo).list();
            if (CollectionUtil.isNotEmpty(dummyConfigurableModels)) {
                return dummyConfigurableModels.get(0);
            }
        }
        return null;
    }

    @Override
    public void saveLink(DummyConfigurableModelDto originModelDto, DummyConfigurableModelDto targetModelDto, DummyConfigurableModelDto modifyModelDto) {
        Map<String, List<DummyConfigurableModelCatagoryDto>> originCategoryMap = originModelDto.getDummyConfigurableModelCatagoryDtos().stream().collect(Collectors.groupingBy(DummyConfigurableModelCatagoryDto::getCategory));
        Map<String, List<DummyConfigurableModelCatagoryDto>> modifyCategoryMap = modifyModelDto.getDummyConfigurableModelCatagoryDtos().stream().collect(Collectors.groupingBy(DummyConfigurableModelCatagoryDto::getCategory));
        // 创建, 更新逻辑
        targetModelDto.getDummyConfigurableModelCatagoryDtos().forEach(targetCateforyDto -> {
            if (targetCateforyDto.getId() == null) { // 创建category, 并创建feature
                List<DummyConfigurableModelCatagoryDto> saveCategoryDto = Lists.newArrayList();
                saveCategoryDto.add(targetCateforyDto);
                dummyConfigurableModelCategoryService.saveByDcmId(targetModelDto.getId(), saveCategoryDto);
            } else { // 创建或更新feature
                List<DummyConfigurableModelFeatureDto> targetFeatureDtos = targetCateforyDto.getDummyConfigurableModelFeatureDtos();
                List<DummyConfigurableModelCatagoryDto> originCatagoryDtos = originCategoryMap.get(targetCateforyDto.getCategory());
                Map<Long, List<DummyConfigurableModelFeatureDto>> originFeatureMap = originCatagoryDtos.get(0).getDummyConfigurableModelFeatureDtos().stream().collect(Collectors.groupingBy(DummyConfigurableModelFeatureDto::getId));
                if (!targetModelDto.getReferenceCtoNumber().equals(originModelDto.getReferenceCtoNumber())) {
                    dummyConfigurableModelCategoryService.update(Wrappers.lambdaUpdate(DummyConfigurableModelCategory.class)
//                            .set(DummyConfigurableModelCategory::getFullCv, CollUtil.join(targetCateforyDto.getFullCvs(), ","))
                            .eq(DummyConfigurableModelCategory::getId, originCatagoryDtos.get(0).getId()));
                }
                List<DummyConfigurableModelCatagoryDto> modifyCatagoryDtos = modifyCategoryMap.get(targetCateforyDto.getCategory());
                Map<String, List<DummyConfigurableModelFeatureDto>> modifyFeatureMap = modifyCatagoryDtos.get(0).getDummyConfigurableModelFeatureDtos().stream().collect(Collectors.groupingBy(DummyConfigurableModelFeatureDto::getDescName));

                targetFeatureDtos.forEach(targetFeatureDto -> {
                    if (targetFeatureDto.getId() == null) {   // 创建feature
                        List<DummyConfigurableModelCatagoryDto> saveCategoryDto = Lists.newArrayList();
                        DummyConfigurableModelCatagoryDto dummyConfigurableModelCatagoryDto = new DummyConfigurableModelCatagoryDto();
                        dummyConfigurableModelCatagoryDto.setId(targetCateforyDto.getId());
                        List<DummyConfigurableModelFeatureDto> saveFeatureDto = Lists.newArrayList();
                        saveFeatureDto.add(targetFeatureDto);
                        dummyConfigurableModelCatagoryDto.setDummyConfigurableModelFeatureDtos(saveFeatureDto);
                        saveCategoryDto.add(dummyConfigurableModelCatagoryDto);
                        dummyConfigurableModelProductFeaturesDescService.saveDcms(saveCategoryDto);
                    } else {
                        // 获取原有的featureDto, 看颜色是否为绿色或者黑色, 如果新的颜色为红色或者橙色则更新final值, 否则 只更新desc的值
                        DummyConfigurableModelFeatureDto originFeatureDto = originFeatureMap.get(targetFeatureDto.getId()).get(0);
                        DummyConfigurableModelFeatureDto modifyFeatureDto = modifyFeatureMap.get(targetFeatureDto.getDescName()).get(0);
                        if (originFeatureDto.getDescName().equals(modifyFeatureDto.getDescName())) { // 没修改feature
                            if (!originFeatureDto.getFinalCvs().equals(modifyFeatureDto.getFinalCvs())) { // 修改了 finalcv
                                targetFeatureDto.setFinalCvs(modifyFeatureDto.getFinalCvs());
                                targetFeatureDto.setFinalColor(DcmConstant.DCM_FEATURE_COLOR_BLACK);
                            } else {
                                if (DcmConstant.DCM_FEATURE_COLOR_BLACK.equals(originFeatureDto.getFinalColor())
                                        && !DcmConstant.DCM_FEATURE_COLOR_GREEN.equals(targetFeatureDto.getFinalColor())) {
                                    targetFeatureDto.setFinalCvs(originFeatureDto.getFinalCvs());
                                    targetFeatureDto.setFinalColor(originFeatureDto.getFinalColor());
                                }
                            }
                        } else {
                            if (!originFeatureDto.getFinalCvs().equals(modifyFeatureDto.getFinalCvs())
                                    && !DcmConstant.DCM_FEATURE_COLOR_GREEN.equals(targetFeatureDto.getFinalColor())) { // 修改了 finalcv
                                targetFeatureDto.setFinalCvs(modifyFeatureDto.getFinalCvs());
                                targetFeatureDto.setFinalColor(DcmConstant.DCM_FEATURE_COLOR_BLACK);
                            }
                        }
                        dummyConfigurableModelProductFeaturesDescService.updateDcms(targetFeatureDto);
                    }
                });
                // 删除feature逻辑 当origin有 target没有
                List<Long> originFeatureIds = originCatagoryDtos.get(0).getDummyConfigurableModelFeatureDtos().stream().map(DummyConfigurableModelFeatureDto::getId).toList();
                List<Long> targetFeatureIds = targetFeatureDtos.stream().map(DummyConfigurableModelFeatureDto::getId).toList();
                List<Long> needRemoveFeatureIds = originFeatureIds.stream().filter(id -> !targetFeatureIds.contains(id)).toList();
                if (CollectionUtil.isNotEmpty(needRemoveFeatureIds)) {
                    dummyConfigurableModelProductFeaturesDescService.removeBatchByIds(needRemoveFeatureIds);
                }
            }
        });
        // 删除category逻辑 当origin有 target没有
        List<Long> originCategoryIds = originModelDto.getDummyConfigurableModelCatagoryDtos().stream().map(DummyConfigurableModelCatagoryDto::getId).toList();
        List<Long> targetCategoryIds = targetModelDto.getDummyConfigurableModelCatagoryDtos().stream().map(DummyConfigurableModelCatagoryDto::getId).toList();
        List<Long> needRemoveCategoryIds = originCategoryIds.stream().filter(id -> !targetCategoryIds.contains(id)).toList();
        if (CollectionUtil.isNotEmpty(needRemoveCategoryIds)) {
            dummyConfigurableModelCategoryService.delCategoriesByCategoryIds(needRemoveCategoryIds);
        }
    }

    @Override
    public String getDcmNumberById(Integer id) {
        DummyConfigurableModel dummyConfigurableModel = getById(id);
        if (dummyConfigurableModel == null) {
            // 没有对象
            throw new DcmBusinessException(BusinessMsgEnum.DCM_NOT_EXIST);
        }
        DummyConfigurableModelMaster dummyConfigurableModelMaster = dummyConfigurableModelMasterService.getById(dummyConfigurableModel.getMasterId());
        if (dummyConfigurableModelMaster == null) {
            // 没有对象
            throw new DcmBusinessException(BusinessMsgEnum.DCM_NOT_EXIST);
        }else{
            return dummyConfigurableModelMaster.getNumber();
        }
    }

    @Override
    public void saveLinkNew(DummyConfigurableModelDto resultDto) {
        delLink(resultDto.getId());
        List<DummyConfigurableModelCatagoryDto> saveCategoryDto = Lists.newArrayList();
        saveCategoryDto.addAll(resultDto.getDummyConfigurableModelCatagoryDtos());
        dummyConfigurableModelCategoryService.saveByDcmId(resultDto.getId(), saveCategoryDto);
    }

    private void delLink(Long id) {
        dummyConfigurableModelCategoryService.delCategoriesByDcmId(id);
    }

    private Integer newMajorVersion(DummyConfigurableModel oldDummyConfigurableModel) {
        DummyConfigurableModel newDummyConfigurableModel = copyNewDCM(oldDummyConfigurableModel);
        // 创建新的对象
        newDummyConfigurableModel.setIteration(1);
        newDummyConfigurableModel.setVersion(VersionUtil.getNextVersion(oldDummyConfigurableModel.getVersion()));
        newDummyConfigurableModel.setBranchId(this.getBaseMapper().getBranchId());
        newDummyConfigurableModel.setState(DcmConstant.DCM_STATUS_DRAFT);
        save(newDummyConfigurableModel);
        // 给老的版本设置非最新状态
        oldDummyConfigurableModel.setLastestAll(false);
        updateById(oldDummyConfigurableModel);
        return newDummyConfigurableModel.getId().intValue();
    }

    private Integer newSecondaryVersion(DummyConfigurableModel oldDummyConfigurableModel) {
        DummyConfigurableModel newDummyConfigurableModel = copyNewDCM(oldDummyConfigurableModel);
        // 创建新的对象
        newDummyConfigurableModel.setIteration(oldDummyConfigurableModel.getIteration() + 1);
        newDummyConfigurableModel.setState(DcmConstant.DCM_STATUS_DRAFT);
        save(newDummyConfigurableModel);
        // 给老的版本设置非最新状态
        oldDummyConfigurableModel.setLastest(0);
        oldDummyConfigurableModel.setLastestAll(false);
        updateById(oldDummyConfigurableModel);
        return newDummyConfigurableModel.getId().intValue();
    }

    private DummyConfigurableModel copyNewDCM(DummyConfigurableModel dummyConfigurableModel) {
        DummyConfigurableModel model = new DummyConfigurableModel();
        BeanUtil.copyProperties(dummyConfigurableModel, model);
        model.setId(null);
        model.setLastest(1);
        model.setLastestAll(true);
        model.setChangedFrom(dummyConfigurableModel.getId());
        model.setCheckoutStatus(1);
        model.setCheckoutTime(DateUtil.date());
        model.setModifyTime(DateUtil.date());
        model.setCheckoutBy(ContextUtil.getCurrentUser());
        model.setModifier(ContextUtil.getCurrentUser());
        return model;
    }
}




